package com.yonyou.ucf.mdf.app.controller.trd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.yms.api.IYmsJdbcApi;
import com.yonyou.iuap.yms.dao.BaseDAO;
import com.yonyou.iuap.yms.param.SQLParameter;
import com.yonyou.ucf.mdd.ext.controller.Authentication;
import com.yonyou.ucf.mdd.ext.exceptions.BusinessException;
import com.yonyou.ucf.mdf.app.util.TenantClearRSAUtils;
import com.yonyou.ypd.bill.basic.utils.PubHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
public class ExtBillController{
    private Logger logger = LoggerFactory.getLogger(ExtBillController.class);
    private static final String YHTACCESSTOKEN = "yht_access_token";
    private static final String dataClearSql = "delete from %s where ytenant_id=?";
    private static final String dataClear_Error = "9999";
    private static final String dataClear_Succes = "0000";

    @Value("${reportUrl}")
    private String reportUrl;
    @Value("${isPremises:false}")
    private Boolean isPremises;
    @Value("${domain.iuap-metadata-designer:}")
    private String metadataDesignerServerUrl;
    @Resource(name = "baseDAO", type = BaseDAO.class)
    private IYmsJdbcApi ymsJdbcApi;

    /**
     * @Description 自定义检查Long型主键档案引用关系
     * curl -X GET \
     *   '{自建引擎统一域名路径}/cust/findLongTypeMetaProperty?domain=自建引擎编码&appCode=应用编码' \
     *   -H 'cookie: 浏览器cookie' \
     *   应用编码可不填就是查整个引擎domain的元数据。可在浏览器上打开业务中台后，新开页签直接这行，get请求
     * @Author yanx
     * @Date 2023/7/4
     */
    @PostMapping("/rest/v1/dataClearByTenant")
    @Authentication(false)
    @ResponseBody
    public Map<String, Object> findLongTypeMetaProperty(@RequestBody Map<String, String> params
            , @RequestParam(value = "appCode", required = false) String appCode
            , HttpServletRequest request, HttpServletResponse response) throws Exception {
        String reqTenantId = params.get("tenantId");
        if (StringUtils.isEmpty(reqTenantId)) {
            throw new BusinessException("dataClearByTenant tenantId is null ,invalid request!");
        }
        String ytenantId = InvocationInfoProxy.getTenantid();
        try {
            if (!isPremises) {
                reqTenantId = TenantClearRSAUtils.decrypt(reqTenantId);
            }
            String userId = InvocationInfoProxy.getUserid();
            if (StringUtils.isEmpty(ytenantId) || "0".equals(reqTenantId)) {
                throw new BusinessException("dataClearByTenant tenantId is null or zero ,invalid request!");
            }
            if (!isPremises && !ytenantId.equals(reqTenantId)) {
                throw new BusinessException("dataClearByTenant not match invocation tenantId ,invalid request!");
            }

            String metaDataRs = this.getMetaDataInfos(reqTenantId, appCode);
            List<Map<String, String>> returnDatas = this.execDataClear(metaDataRs, reqTenantId);

            return buildSuccessRs(reqTenantId, returnDatas);
        } catch (Exception e) {
            return buildErrorRs("租户数据清理失败: " + e.getMessage(), reqTenantId);
        }
    }

    private Map<String, Object> buildErrorRs(String msg, String tenantId) {
        Map<String, Object> rsMap = new HashMap<>(4);
        rsMap.put("code", dataClear_Error);
        rsMap.put("msg", msg);
        if (null != tenantId) {
            rsMap.put("tenantId", tenantId);
        }

        return rsMap;
    }

    private Map<String, Object> buildSuccessRs(String tenantId, Object data) {
        Map<String, Object> rsMap = new HashMap<>(4);
        rsMap.put("code", dataClear_Succes);
        rsMap.put("msg", "执行成功");
        if (null != tenantId) {
            rsMap.put("tenantId", tenantId);
        }
        if (null != data) {
            rsMap.put("data", data);
        }

        return rsMap;
    }

    private List<Map<String, String>> execDataClear(String metaDataRs, String ytenantId) {

        List<Map<String, String>> returnDatas = new ArrayList<>();
        if (null != metaDataRs && metaDataRs.startsWith("{")) {
            JSONObject jsonRs = JSON.parseObject(metaDataRs);
            JSONArray arrayDatas = jsonRs.getJSONArray("data");
            if (null != arrayDatas && !arrayDatas.isEmpty()) {
                int sizeDatas = arrayDatas.size();
                for (int i = 0; i < sizeDatas; i++) {
                    JSONObject jsonData = arrayDatas.getJSONObject(i);
                    String id = jsonData.getString("id");
                    String uri = jsonData.getString("uri");
                    String displayName = jsonData.getString("displayName");
                    String tableName = jsonData.getString("tableName");

                    Map<String, String> data = new LinkedHashMap<>();
                    data.put("元数据uri", uri);
                    data.put("表名", tableName);
                    returnDatas.add(data);
                    String rsMsg = this.execSingleDataClear(tableName, ytenantId);
                    data.put("清理结果", rsMsg);

//                    JSONArray arrayOwnedAttribute = jsonData.getJSONArray("ownedAttribute");
//                    if (null != arrayOwnedAttribute && !arrayOwnedAttribute.isEmpty()) {
//                        for (Object o : arrayOwnedAttribute) {
//                            JSONObject jsonAttribute = (JSONObject) o;
//                            String biztype = jsonAttribute.getString("biztype");
//                            if (BIZTYPE_QUOTE.equals(biztype)) {
//                                JSONObject jsonDataType = jsonAttribute.getJSONObject("dataType");
//                                if (null == jsonDataType) {
//                                    continue;
//                                }
//                                String quoteUri = jsonDataType.getString("uri");
//                                if (setCheckUris.contains(quoteUri)) {// 属性的引用类型在指定范围内，打印信息
//                                    String attrName = jsonAttribute.getString("name");
//                                    String fieldName = jsonAttribute.getString("fieldName");
//                                    String attrDisplayName = jsonAttribute.getString("displayName");
//                                    Map<String, String> data = new LinkedHashMap<>();
//                                    data.put("表名", tableName);
//                                    data.put("列名", fieldName);
//                                    data.put("实体uri", uri);
//                                    data.put("实体id", uri);
//                                    data.put("实体名", displayName);
//                                    data.put("属性编码", attrName);
//                                    data.put("属性名", attrDisplayName);
//
//                                    returnDatas.add(data);
//                                }
//                            }
//                        }
//                    }
                }
            }

        }

        return returnDatas;
    }

    private String getMetaDataInfos(String ytenantId, String appCode) throws Exception {
        StringBuffer urlBuffer = new StringBuffer(metadataDesignerServerUrl);
        urlBuffer.append("/metadata-designer/class/domain?domain=")
                .append("developplatform")// domain
                .append("&tenantId=")
                .append(ytenantId);
        if (null != appCode) {
            urlBuffer.append("&appCode=").append(appCode);
        }
        String url = urlBuffer.toString();
        String resultData = PubHttpUtil.sendGet(url, new HashMap<>(), new HashMap<>());

        return resultData;
    }

    private String execSingleDataClear(String tableName, String ytenantId) {
        String rsMsg = "清理成功";
        String delSql = String.format(dataClearSql, tableName);
        SQLParameter sqlParameter = new SQLParameter();
        sqlParameter.addParam(ytenantId);

        try {
            ymsJdbcApi.update(delSql, sqlParameter);
        } catch (Exception e) {
            rsMsg = "清理失败: " + e.getMessage();
        }

        return rsMsg;
    }

}
